package com.bzr.emos.wx.config.jwt;

import com.bzr.emos.wx.Service.UserService;
import com.bzr.emos.wx.db.pojo.WechatUsers;
import com.bzr.emos.wx.util.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        log.info("JWT校验");
        //放行/login 请求
        String requestURI = request.getRequestURI();
        if (
                 ("/login").equals(requestURI)
               ||("/verify/VerifyLogin").equals(requestURI)
               ||("/verify/activation").equals(requestURI)
               ||("/register/avatar").equals(requestURI)
        ) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = resolveToken(request);

        if (token==null&&request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("DlToken".equals(cookie.getName())) {
                    token=cookie.getValue();
                }
            }
        }



        if (token != null) {
            try {
                String userId = JwtUtils.validateToken(token);
                List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                        userId, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(auth);

            } catch (RuntimeException e) {
                // Token验证失败，返回401
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {



        String bearerToken = request.getHeader("Authorization");

        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}